// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;
using InterpriseSuiteEcommerceCommon.Extensions;
using System.Linq;

namespace InterpriseSuiteEcommerceCommon
{
    /// <summary>
    /// Summary description for CommonLogic.
    /// </summary>
    public class CommonLogic
    {
        // this class now contains general support routines, but no "store" specific logic.
        // Store specific logic has been moved to the new AppLogic class

        static private Random RandomGenerator = new Random(System.DateTime.Now.Millisecond);

        public CommonLogic() { }

        public static string[] SupportedImageTypes = { ".jpg", ".gif", ".png" };

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static bool IsStringNullOrEmpty(string value)
        {
            return value.IsNullOrEmpty();
        }

        public static bool IsValidGuid(string guidStringToTest)
        {
            try
            {
                Guid g = new Guid(guidStringToTest);
                return true;
            }
            catch { }

            return false;
        }

        public static string GenerateRandomCode(int NumDigits)
        {
            string s = "";
            for (int i = 1; i <= NumDigits; i++)
            {
                s += RandomGenerator.Next(10).ToString();
            }
            return s;
        }

        // this is good enough for what we need to use it for. it is not scientifically 100% valid for all cases!!
        public static bool StringIsAlreadyHTMLEncoded(string s)
        {
            return s.Contains("&nbsp;") || s.Contains("&quot;") || s.Contains("&amp;") || s.Contains("&lt;") || s.Contains("&gt;");
        }

        public static string CleanLevelOne(string s)
        {
            // specify ALLOWED chars here, anything else is removed due to ^ (not) operator:
            return Regex.Replace(s, @"[^\w\s\.\-!@#\$%\^&\*\(\)\+=\?\/\{\}\[\]\\\|~`';:<>,_""]", "", RegexOptions.Compiled);
        }

        // allows only space chars
        public static string CleanLevelTwo(string s)
        {
            // specify ALLOWED chars here, anything else is removed due to ^ (not) operator:
            return Regex.Replace(s, @"[^\w \.\-!@#\$%\^&\*\(\)\+=\?\/\{\}\[\]\\\|~`';:<>,_""]", "", RegexOptions.Compiled);
        }

        // allows a-z, A-Z, 0-9 and space char, period, $ sign, % sign, and comma
        public static string CleanLevelThree(string s)
        {
            // specify ALLOWED chars here, anything else is removed due to ^ (not) operator:
            return Regex.Replace(s, @"[^\w \.\$%,]", "", RegexOptions.Compiled);
        }

        // allows a-z, A-Z, 0-9 and space char
        public static string CleanLevelFour(string s)
        {
            // specify ALLOWED chars here, anything else is removed due to ^ (not) operator:
            return Regex.Replace(s, @"[^\w ]", "", RegexOptions.Compiled);
        }

        // allows a-z, A-Z, 0-9
        public static string CleanLevelFive(string s)
        {
            // specify ALLOWED chars here, anything else is removed due to ^ (not) operator:
            return Regex.Replace(s, @"[^\w]", "", RegexOptions.Compiled);
        }

        public static System.Drawing.Image LoadImage(string url)
        {
            string imgName = SafeMapPath(url);
            Bitmap bmp = new Bitmap(imgName);
            return bmp;
        }

        // can use either text copyright, or image copyright, or both:
        // imgPhoto is image (memory) on which to add copyright text/mark
        public static System.Drawing.Image AddWatermark(System.Drawing.Image imgPhoto, string CopyrightText, string CopyrightImageUrl)
        {
            int phWidth = imgPhoto.Width;
            int phHeight = imgPhoto.Height;

            //create a Bitmap the Size of the original photograph
            Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            //load the Bitmap into a Graphics object 
            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
            grPhoto.SmoothingMode = SmoothingMode.HighQuality;
            grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
            grPhoto.CompositingQuality = CompositingQuality.HighQuality;
            //create a image object containing the watermark
            Image imgWatermark = null;
            int wmWidth = 0;
            int wmHeight = 0;
            if (CopyrightImageUrl.Length != 0)
            {
                imgWatermark = new Bitmap(SafeMapPath(CopyrightImageUrl));
                wmWidth = imgWatermark.Width;
                wmHeight = imgWatermark.Height;
            }

            //------------------------------------------------------------
            //Step #1 - Insert Copyright message
            //------------------------------------------------------------

            //Set the rendering quality for this Graphics object
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

            //Draws the photo Image object at original size to the graphics object.
            grPhoto.DrawImage(
                imgPhoto,                               // Photo Image object
                new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
                0,                                      // x-coordinate of the portion of the source image to draw. 
                0,                                      // y-coordinate of the portion of the source image to draw. 
                phWidth,                                // Width of the portion of the source image to draw. 
                phHeight,                               // Height of the portion of the source image to draw. 
                GraphicsUnit.Pixel);                    // Units of measure 

            //-------------------------------------------------------
            //to maximize the size of the Copyright message we will 
            //test multiple Font sizes to determine the largest posible 
            //font we can use for the width of the Photograph
            //define an array of point sizes you would like to consider as possiblities
            //-------------------------------------------------------
            int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };

            Font crFont = null;
            SizeF crSize = new SizeF();

            //Loop through the defined sizes checking the length of the Copyright string
            //If its length in pixles is less then the image width choose this Font size.
            for (int i = 0; i < 7; i++)
            {
                //set a Font object to Arial (i)pt, Bold
                crFont = new Font("arial", sizes[i], FontStyle.Bold);
                //Measure the Copyright string in this Font
                crSize = grPhoto.MeasureString(CopyrightText, crFont);

                if ((ushort)crSize.Width < (ushort)phWidth)
                    break;
            }

            //Since all photographs will have varying heights, determine a 
            //position 5% from the bottom of the image
            int OffsetPercentage = AppLogic.AppConfigUSInt("Watermark.OffsetFromBottomPercentage");
            if (OffsetPercentage == 0)
            {
                OffsetPercentage = 5;
            }
            int yPixlesFromBottom = (int)(phHeight * (OffsetPercentage / 100.0));

            //Now that we have a point size use the Copyrights string height 
            //to determine a y-coordinate to draw the string of the photograph
            float yPosFromBottom = ((phHeight - yPixlesFromBottom) - (crSize.Height / 2.0F));

            //Determine its x-coordinate by calculating the center of the width of the image
            float xCenterOfImg = (phWidth / 2);

            //Define the text layout by setting the text alignment to centered
            StringFormat StrFormat = new StringFormat();
            StrFormat.Alignment = StringAlignment.Center;

            //define a Brush which is semi trasparent black (Alpha set to 153)
            SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0));

            //Draw the Copyright string
            grPhoto.DrawString(CopyrightText,                 //string of text
                crFont,                                   //font
                semiTransBrush2,                           //Brush
                new PointF(xCenterOfImg + 1, yPosFromBottom + 1),  //Position
                StrFormat);

            //define a Brush which is semi trasparent white (Alpha set to 153)
            SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));

            //Draw the Copyright string a second time to create a shadow effect
            //Make sure to move this text 1 pixel to the right and down 1 pixel
            grPhoto.DrawString(CopyrightText,                 //string of text
                crFont,                                   //font
                semiTransBrush,                           //Brush
                new PointF(xCenterOfImg, yPosFromBottom),  //Position
                StrFormat);                               //Text alignment

            //------------------------------------------------------------
            //Step #2 - Insert Watermark image
            //------------------------------------------------------------
            if (imgWatermark != null)
            {
                //Create a Bitmap based on the previously modified photograph Bitmap
                Bitmap bmWatermark = new Bitmap(bmPhoto);
                bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
                //Load this Bitmap into a new Graphic Object
                Graphics grWatermark = Graphics.FromImage(bmWatermark);

                //To achieve a transulcent watermark we will apply (2) color 
                //manipulations by defineing a ImageAttributes object and 
                //seting (2) of its properties.
                ImageAttributes imageAttributes = new ImageAttributes();

                //The first step in manipulating the watermark image is to replace 
                //the background color with one that is trasparent (Alpha=0, R=0, G=0, B=0)
                //to do this we will use a Colormap and use this to define a RemapTable
                ColorMap colorMap = new ColorMap();

                //Watermark image should be defined with a background of 100% Green this will
                //be the color we search for and replace with transparency
                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

                ColorMap[] remapTable = { colorMap };

                imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                //The second color manipulation is used to change the opacity of the 
                //watermark.  This is done by applying a 5x5 matrix that contains the 
                //coordinates for the RGBA space.  By setting the 3rd row and 3rd column 
                //to 0.1f we achive a level of opacity
                float[][] colorMatrixElements = {   new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},       
													new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},        
													new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},        
													new float[] {0.0f,  0.0f,  0.0f,  0.1f, 0.0f},        
													new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}};
                float WatermarkOpacity = AppLogic.AppConfigUSSingle("Watermark.Opacity");
                if (WatermarkOpacity != 0.0F)
                {
                    colorMatrixElements[3][3] = WatermarkOpacity;
                }
                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);

                imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
                    ColorAdjustType.Bitmap);

                //For this example we will place the watermark in center of the photograph.

                int xPosOfWm = ((phWidth - wmWidth) / 2);
                int yPosOfWm = ((phHeight - wmHeight) / 2);

                grWatermark.DrawImage(imgWatermark,
                    new Rectangle(xPosOfWm, yPosOfWm, wmWidth, wmHeight),  //Set the detination Position
                    0,                  // x-coordinate of the portion of the source image to draw. 
                    0,                  // y-coordinate of the portion of the source image to draw. 
                    wmWidth,            // Watermark Width
                    wmHeight,		    // Watermark Height
                    GraphicsUnit.Pixel, // Unit of measurment
                    imageAttributes);   //ImageAttributes Object
                bmPhoto = bmWatermark;
                grWatermark.Dispose();
            }
            grPhoto.Dispose();
            if (imgWatermark != null)
            {
                imgWatermark.Dispose();
            }
            return bmPhoto;
        }

        public static string PageParamsAsXml(bool IncludeRootNode, string RootNodeName, bool ExcludeVldtFields)
        {
            StringBuilder tmpS = new StringBuilder(4096);
            if (IncludeRootNode)
            {
                if (RootNodeName.Length == 0)
                {
                    tmpS.Append("<root>");
                }
                else
                {
                    tmpS.Append("<" + RootNodeName + ">");
                }
            }
            tmpS.Append("<QueryString>");
            for (int i = 0; i <= HttpContext.Current.Request.QueryString.Count - 1; i++)
            {
                string FieldName = HttpContext.Current.Request.QueryString.Keys[i].ToString();
                string FieldValue = HttpContext.Current.Request.QueryString[HttpContext.Current.Request.QueryString.Keys[i]].ToString();
                if (!ExcludeVldtFields || !FieldName.EndsWith("_vldt"))
                {
                    tmpS.Append(string.Format("<{0}>{1}</{2}>", FieldName, XmlCommon.XmlEncode(FieldValue), FieldName));
                }
            }
            tmpS.Append("</QueryString>");

            tmpS.Append("<Form>");
            for (int i = 0; i <= HttpContext.Current.Request.Form.Count - 1; i++)
            {
                string FieldName = HttpContext.Current.Request.Form.Keys[i].ToString();
                string FieldValue = HttpContext.Current.Request.Form[HttpContext.Current.Request.Form.Keys[i]].ToString();
                if (!ExcludeVldtFields || !FieldName.EndsWith("_vldt"))
                {
                    tmpS.Append(string.Format("<{0}>{1}</{2}>", FieldName, XmlCommon.XmlEncode(FieldValue), FieldName));
                }
            }
            tmpS.Append("</Form>");

            if (IncludeRootNode)
            {
                if (RootNodeName.Length == 0)
                {
                    tmpS.Append("</root>");
                }
                else
                {
                    tmpS.Append("</" + RootNodeName + ">");
                }
            }
            return tmpS.ToString();
        }

        public static string UTF8ByteArrayToString(Byte[] characters)
        {

            UTF8Encoding encoding = new UTF8Encoding();
            string constructedString = encoding.GetString(characters);
            return constructedString;
        }

        public static Byte[] StringToUTF8ByteArray(string pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }

        /// <summary>
        /// Utility function to check if a string value is included within the commadelimited string to match with
        /// </summary>
        /// <param name="stringValue">the string to look for</param>
        /// <param name="commaDelimitedList">the comma delimited string to search at</param>
        /// <returns></returns>
        public static bool StringInCommaDelimitedStringList(string stringValue, string commaDelimitedList)
        {
            try
            {
                if (CommonLogic.IsStringNullOrEmpty(stringValue) ||
                    CommonLogic.IsStringNullOrEmpty(commaDelimitedList))
                {
                    return false;
                }

                string[] individualValues = commaDelimitedList.Split(',');

                foreach (string valueToMatch in individualValues)
                {
                    if (valueToMatch.Trim().Equals(stringValue.Trim(), StringComparison.InvariantCultureIgnoreCase))
                    {
                        return true;
                    }
                }
            }
            catch
            {
                return false;
            }

            return false;
        }

        public static bool IntegerIsInIntegerList(string SearchInt, string ListOfInts)
        {
            try
            {
                string target = SearchInt.ToString();
                if (ListOfInts.Length == 0)
                {
                    return false;
                }
                string[] s = ListOfInts.Split(',');
                foreach (string spat in s)
                {
                    if (target == spat)
                    {
                        return true;
                    }
                }
                return false;
            }
            catch
            {
                return false;
            }
        }

        public static string GetChart(string ReportTitle, string XTitle, string YTitle, string Height, string Width, bool ChartIs3D, string ChartTypeSpec, string Series1Name, string Series2Name, string DateSeries, string DS1Values, string DS2Values)
        {
            StringBuilder tmpS = new StringBuilder(10000);

            tmpS.Append("<p align=\"center\"><b><big>" + ReportTitle.Replace("|", ", ") + "</big></b></p>\n");
            tmpS.Append("<APPLET CODE=\"javachart.applet." + ChartTypeSpec + "\" ARCHIVE=\"" + ChartTypeSpec + ".jar\" WIDTH=100% HEIGHT=500>\n");
            tmpS.Append("<param name=\"appletKey \" value=\"6080-632\">\n");
            tmpS.Append("<param name=\"CopyrightNotification\" value=\"KavaChart is a copyrighted work, and subject to full legal protection\">\n");
            tmpS.Append("<param name=\"delimiter\" value=\"|\">\n");
            tmpS.Append("<param name=\"labelsOn\" value=\"false\">\n");
            tmpS.Append("<param name=\"useValueLabels\" value=\"false\">\n");
            tmpS.Append("<param name=\"labelPrecision\" value=\"0\">\n");
            tmpS.Append("<param name=\"barClusterWidth\" value=\"0.58\">\n");
            tmpS.Append("<param name=\"dataset0LabelFont\" value=\"Serif|12|0\">\n");
            tmpS.Append("<param name=\"dataset0LabelColor\" value=\"000000\">\n");
            tmpS.Append("<param name=\"dataset1LabelFont\" value=\"Serif|12|0\">\n");
            tmpS.Append("<param name=\"dataset1LabelColor\" value=\"000000\">\n");
            tmpS.Append("<param name=\"backgroundColor\" value=\"ffffff\">\n");
            tmpS.Append("<param name=\"backgroundOutlining\" value=\"false\">\n");
            tmpS.Append("<param name=\"3D\" value=\"" + ChartIs3D.ToString(CultureInfo.InvariantCulture).ToLower() + "\">\n");
            tmpS.Append("<param name=\"YDepth\" value=\"15\">\n");
            tmpS.Append("<param name=\"XDepth\" value=\"10\">\n");
            tmpS.Append("<param name=\"outlineLegend\" value=\"false\">\n");
            tmpS.Append("<param name=\"outlineColor\" value=\"000000\">\n");
            tmpS.Append("<param name=\"dataset0Name\" value=\"" + Series1Name + "\">\n");
            tmpS.Append("<param name=\"dataset0Labels\" value=\"false\">\n");
            tmpS.Append("<param name=\"dataset0Color\" value=\"" + CommonLogic.IIF(Series1Name == "Anons", "00cccc", "0066cc") + "\">\n");
            tmpS.Append("<param name=\"dataset0Outlining\" value=\"false\">\n");
            if (Series2Name.Length != 0)
            {
                tmpS.Append("<param name=\"dataset1Name\" value=\"" + Series2Name + "\">\n");
                tmpS.Append("<param name=\"dataset1Labels\" value=\"false\">\n");
                tmpS.Append("<param name=\"dataset1Color\" value=\"0066cc\">\n");
                tmpS.Append("<param name=\"dataset1Outlining\" value=\"false\">\n");
            }
            tmpS.Append("   <param name=\"backgroundGradient\" value=\"2\">\n");
            tmpS.Append("   <param name=\"backgroundTexture\" value=\"2\">\n");
            tmpS.Append("   <param name=\"plotAreaColor\" value=\"ffffcc\">\n");
            tmpS.Append("   <param name=\"backgroundSecondaryColor\" value=\"ccccff\">\n");
            tmpS.Append("   <param name=\"backgroundGradient\" value=\"2\">\n");
            tmpS.Append("   <param name=\"yAxisTitle\" value=\"" + YTitle + "\">\n");
            tmpS.Append("<param name=\"yAxisLabelColor\" value=\"000000\">\n");
            tmpS.Append("<param name=\"yAxisLineColor\" value=\"000000\">\n");
            tmpS.Append("<param name=\"yAxisGridColor\" value=\"000000\">\n");
            tmpS.Append("<param name=\"yAxisGridWidth\" value=\"1\">\n");
            tmpS.Append("<param name=\"yAxisTickColor\" value=\"000000\">\n");
            tmpS.Append("<param name=\"yAxisOptions\" value=\"gridOn|leftAxis,\">\n");
            tmpS.Append("   <param name=\"xAxisTitle\" value=\"" + XTitle + "\">\n");
            tmpS.Append("<param name=\"xAxisLabelColor\" value=\"000000\">\n");
            tmpS.Append("<param name=\"xAxisLineColor\" value=\"000000\">\n");
            tmpS.Append("<param name=\"xAxisTickColor\" value=\"000000\">\n");
            tmpS.Append("<param name=\"xAxisOptions\" value=\"bottomAxis,\">\n");
            tmpS.Append("<param name=\"legendOn\" value=\"true\">\n");
            tmpS.Append("<param name=\"legendllX\" value=\".00\">\n");
            tmpS.Append("<param name=\"legendllY\" value=\".90\">\n");
            tmpS.Append("<param name=\"legendLabelFont\" value=\"Serif|12|0\">\n");
            tmpS.Append("<param name=\"legendLabelColor\" value=\"000000\">\n");
            tmpS.Append("<param name=\"legendColor\" value=\"ffffff\">\n");
            tmpS.Append("<param name=\"legendOutlining\" value=\"false\">\n");
            tmpS.Append("<param name=\"iconWidth\" value=\"0.03\">\n");
            tmpS.Append("<param name=\"iconHeight\" value=\"0.02\">\n");
            tmpS.Append("<param name=\"iconGap\" value=\"0.01\">\n");
            tmpS.Append("<param name=\"dwellUseDatasetName\" value=\"false\">\n");
            tmpS.Append("<param name=\"dwellUseYValue\" value=\"true\">\n");
            tmpS.Append("<param name=\"dwellYString\" value=\"Y: #\">\n");
            tmpS.Append("<param name=\"dwellUseXValue\" value=\"false\">\n");
            tmpS.Append("<param name=\"dwellUseLabelString\" value=\"false\">\n");

            // START DATA:
            tmpS.Append("<param name=\"xAxisLabelAngle\"  value=\"90\">\n");
            tmpS.Append("<param name=\"xAxisLabels\"  value=\"" + DateSeries + "\">\n");
            tmpS.Append("<param name=\"dataset0yValues\" value=\"" + DS1Values.Replace("$", "").Replace(",", "") + "\">\n");
            if (Series2Name.Length != 0)
            {
                tmpS.Append("<param name=\"dataset1yValues\" value=\"" + DS2Values.Replace("$", "").Replace(",", "") + "\">\n");
            }
            // END DATA

            tmpS.Append("</APPLET>\n");
            return tmpS.ToString();
        }

        public static string GenerateHtmlEditor(string FieldID)
        {
            StringBuilder tmpS = new StringBuilder(4096);
            tmpS.Append("\n<script type=\"text/javascript\">\n<!--\n");
            tmpS.Append("editor_generate('" + FieldID + "');\n\n");
            tmpS.Append("//-->\n</script>\n");
            return tmpS.ToString();
        }

        public static long GetImageSize(string imgname)
        {
            string imgfullpath = SafeMapPath(imgname);
            try
            {
                FileInfo fi = new FileInfo(imgfullpath);
                long l = fi.Length;
                fi = null;
                return l;
            }
            catch
            {
                return 0;
            }
        }

        public static string GetFormInput(bool ExcludeVldtFields, string separator)
        {
            StringBuilder tmpS = new StringBuilder(10000);
            bool first = true;
            for (int i = 0; i < HttpContext.Current.Request.Form.Count; i++)
            {
                bool okField = true;
                if (ExcludeVldtFields)
                {
                    if (HttpContext.Current.Request.Form.Keys[i].IndexOf("_VLDT", StringComparison.InvariantCultureIgnoreCase) != -1)
                    {
                        okField = false;
                    }
                }
                if ("__EVENTTARGET".Equals(HttpContext.Current.Request.Form.Keys[i], StringComparison.InvariantCultureIgnoreCase) ||
                    "__EVENTARGUMENT".Equals(HttpContext.Current.Request.Form.Keys[i], StringComparison.InvariantCultureIgnoreCase) ||
                    "__VIEWSTATE".Equals(HttpContext.Current.Request.Form.Keys[i], StringComparison.InvariantCultureIgnoreCase))
                {
                    okField = false;
                }
                if (okField)
                {
                    if (!first)
                    {
                        tmpS.Append(separator);
                    }
                    tmpS.Append("<b>" + HttpContext.Current.Request.Form.Keys[i] + "</b>=" + HttpContext.Current.Request.Form[HttpContext.Current.Request.Form.Keys[i]]);
                    first = false;
                }
            }
            return tmpS.ToString();
        }

        public static string GetQueryStringInput(bool ExcludeVldtFields, string separator)
        {
            StringBuilder tmpS = new StringBuilder(10000);
            bool first = true;
            for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)
            {
                bool okField = true;
                if (ExcludeVldtFields)
                {
                    if (HttpContext.Current.Request.QueryString.Keys[i].IndexOf("_VLDT", StringComparison.InvariantCultureIgnoreCase) != -1)
                    {
                        okField = false;
                    }
                }
                if (okField)
                {
                    if (!first)
                    {
                        tmpS.Append(separator);
                    }
                    tmpS.Append("<b>" + HttpContext.Current.Request.QueryString.Keys[i] + "</b>=" + HttpContext.Current.Request.QueryString[HttpContext.Current.Request.QueryString.Keys[i]]);
                    first = false;
                }
            }
            return tmpS.ToString();
        }

        public static string GetFormInputAsXml(bool ExcludeVldtFields, string RootNode)
        {
            StringBuilder tmpS = new StringBuilder(10000);
            tmpS.Append("<" + RootNode + ">");
            for (int i = 0; i < HttpContext.Current.Request.Form.Count; i++)
            {
                bool okField = true;
                if (ExcludeVldtFields)
                {
                    if (HttpContext.Current.Request.Form.Keys[i].IndexOf("_VLDT", StringComparison.InvariantCultureIgnoreCase) != -1)
                    {
                        okField = false;
                    }
                }
                if (okField)
                {
                    string nodename = XmlCommon.XmlEncode(HttpContext.Current.Request.Form.Keys[i]);
                    string nodeval = XmlCommon.XmlEncode(HttpContext.Current.Request.Form[HttpContext.Current.Request.Form.Keys[i]]);
                    tmpS.Append("<" + nodename + ">");
                    tmpS.Append(nodeval);
                    tmpS.Append("</" + nodename + ">");
                }
            }
            tmpS.Append("</" + RootNode + ">");
            return tmpS.ToString();
        }

        public static string GetQueryStringInputAsXml(bool ExcludeVldtFields, string RootNode)
        {
            StringBuilder tmpS = new StringBuilder(10000);
            tmpS.Append("<" + RootNode + ">");
            for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)
            {
                bool okField = true;
                if (ExcludeVldtFields)
                {
                    if (HttpContext.Current.Request.QueryString.Keys[i].IndexOf("_VLDT", StringComparison.InvariantCultureIgnoreCase) != -1)
                    {
                        okField = false;
                    }
                }
                if (okField)
                {
                    string nodename = XmlCommon.XmlEncode(HttpContext.Current.Request.QueryString.Keys[i]);
                    string nodeval = XmlCommon.XmlEncode(HttpContext.Current.Request.QueryString[HttpContext.Current.Request.QueryString.Keys[i]]);
                    tmpS.Append("<" + nodename + ">");
                    tmpS.Append(nodeval);
                    tmpS.Append("</" + nodename + ">");
                }
            }
            tmpS.Append("</" + RootNode + ">");
            return tmpS.ToString();
        }

        /// <summary>
        /// Composes the returnUrl query string into 1 chunk of string. 
        /// Escapes the &amp; and = characters on the string to preserve the original url if it has additonal query strings
        /// so that it will not get truncated on the next page that will use the returnUrl value.
        /// The code that will use this value should use ReturnUrlDecode to properly interpret the original url passed
        /// Sample:
        /// http://localhost/InterpriseSuiteEcommerce70/p-1-simple-product-1.aspx?hello=world
        /// Becomes:
        /// http://localhost/InterpriseSuiteEcommerce70/p-1-simple-product-1.aspx?hello$world
        /// </summary>
        /// <param name="returnUrl">The return url string to be used on the query string</param>
        /// <returns></returns>
        public static string ReturnURLEncode(string returnUrl)
        {
            return returnUrl.Replace('&', '|').Replace('=', '$');
        }

        /// <summary>
        /// Decodes the returnUrl string that was originally encoded by calling  ReturnUrlEncode
        /// </summary>
        /// <param name="returnUrl">The returnUrl querystring that was originally ReturnUrlEncoded</param>
        /// <returns></returns>
        public static string ReturnURLDecode(string returnUrl)
        {
            return returnUrl.Replace('|', '&').Replace('$', '=');
        }

        /// <summary>
        /// Gets the current page name together with additional query strings if any
        /// This method honors the current page if it's url-rewrited + any other query strings
        /// i.e. http://localhost/InterpriseSuiteEcommerce70/p-1-simple-product-1.aspx?hello=world
        /// The example holds 3 query strings even though it's url rewrited : ProductID, SEName and Hello
        /// It will return the url in the original format plus append any additional query strings
        /// </summary>
        /// <returns></returns>
        public static string GetThisPageUrlWithQueryString()
        {
            return GetThisPageUrlWithQueryString(string.Empty);
        }

        //some more query string routines
        /// <summary>
        /// Gets the current page name together with additional query strings if any
        /// This method honors the current page if it's url-rewrited + any other query strings
        /// i.e. http://localhost/InterpriseSuiteEcommerce70/p-1-simple-product-1.aspx?hello=world
        /// The example holds 3 query strings even though it's url rewrited : ProductID, SEName and Hello
        /// It will return the url in the original format plus append any additional query strings
        /// </summary>
        /// <param name="additionalQueryStringsInNameValuePair">The additional query strings in name=value&amp;name=value format</param>
        /// <returns></returns>
        public static string GetThisPageUrlWithQueryString(string additionalQueryStringsInNameValuePair)
        {
            return GetThisPageUrlWithQueryString(additionalQueryStringsInNameValuePair, true);
        }

        /// <summary>
        /// Gets the current page name together with additional query strings if any
        /// This method honors the current page if it's url-rewrited + any other query strings
        /// i.e. http://localhost/InterpriseSuiteEcommerce70/p-1-simple-product-1.aspx?hello=world
        /// The example holds 3 query strings even though it's url rewrited : ProductID, SEName and Hello
        /// It will return the url in the original format plus append any additional query strings
        /// </summary>
        /// <param name="additionalQueryStringsInNameValuePair">The additional query strings in name=value&amp;name=value format</param>
        /// <param name="encodeValues">The flag whether to url encode the values, should always default this to true</param>
        /// <returns></returns>
        public static string GetThisPageUrlWithQueryString(string additionalQueryStringsInNameValuePair, bool encodeValues)
        {
            // NOTE:
            //  If the current url is url-rewrited, we must honor the current format
            StringBuilder url = new StringBuilder();

            string pageName = string.Empty;

            if (HttpContext.Current.Items["RequestedPage"] != null)
            {
                pageName = HttpContext.Current.Items["RequestedPage"].ToString();
            }
            else
            {
                pageName = CommonLogic.GetThisPageName(false);
            }

            url.Append(pageName);

            // our data structure to hold temporarily the query name value pairs
            Dictionary<string, string> allQueryStrings = new Dictionary<string, string>();

            string originalQueryStringsInNameValuePair = string.Empty;

            if (HttpContext.Current.Items["RequestedQuerystring"] != null)
            {
                originalQueryStringsInNameValuePair = HttpContext.Current.Items["RequestedQuerystring"].ToString();
            }
            else
            {
                originalQueryStringsInNameValuePair = HttpContext.Current.Request.Url.Query;
            }

            if (originalQueryStringsInNameValuePair.StartsWith("?"))
            {
                originalQueryStringsInNameValuePair = originalQueryStringsInNameValuePair.Remove(0, 1);
            }

            string[] originalQueryStrings = originalQueryStringsInNameValuePair.Split('&');

            // first add the original query strings if any            
            if (originalQueryStrings.Length > 0)
            {
                foreach (string queryStringNameValuePair in originalQueryStrings)
                {
                    string[] queryStringValues = queryStringNameValuePair.Split('=');
                    if (queryStringValues.Length == 2)
                    {
                        string queryStringName = queryStringValues[0];
                        string queryStringValue = queryStringValues[1];

                        // let's make sure we have no duplicates in the query string
                        // if we have any, we'll use the first one
                        if (!allQueryStrings.ContainsKey(queryStringName))
                        {
                            allQueryStrings.Add(queryStringName, queryStringValue);
                        }
                    }
                }
            }

            // now let's add the additional query strings if we have any
            string[] additionalQueryStrings = additionalQueryStringsInNameValuePair.Split('&');
            if (additionalQueryStrings.Length > 0)
            {
                foreach (string queryStringNameValuePair in additionalQueryStrings)
                {
                    string[] queryStringValues = queryStringNameValuePair.Split('=');
                    if (queryStringValues.Length == 2)
                    {
                        string queryStringName = queryStringValues[0];
                        string queryStringValue = queryStringValues[1];

                        // let's make sure we have no duplicates in the query string
                        // if we have any, we'll use the first one
                        if (!allQueryStrings.ContainsKey(queryStringName))
                        {
                            allQueryStrings.Add(queryStringName, queryStringValue);
                        }
                    }
                }
            }

            // check if we have query strings
            if (allQueryStrings.Count > 0)
            {
                url.Append("?");

                int ctr = 0;
                foreach (KeyValuePair<string, string> queryString in allQueryStrings)
                {
                    if (ctr != 0)
                    {
                        url.Append("&");
                    }

                    url.AppendFormat(
                        "{0}={1}",
                        HttpUtility.UrlEncode(queryString.Key),
                        CommonLogic.IIF(encodeValues, HttpUtility.UrlEncode(queryString.Value), queryString.Value));

                    ctr++;
                }
            }

            return url.ToString();
        }

        // these are used for VB.NET compatibility
        public static DevExpress.XtraReports.UI.XtraReport IIF(bool condition, DevExpress.XtraReports.UI.XtraReport a, DevExpress.XtraReports.UI.XtraReport b)
        {
            if (condition)
            {
                return a;
            }
            return b;
        }

        public static int IIF(bool condition, int a, int b)
        {
            int x = 0;
            if (condition)
            {
                x = a;
            }
            else
            {
                x = b;
            }
            return x;
        }

        public static bool IIF(bool condition, bool a, bool b)
        {
            bool x = false;
            if (condition)
            {
                x = a;
            }
            else
            {
                x = b;
            }
            return x;
        }
        public static Single IIF(bool condition, Single a, Single b)
        {
            float x = 0;
            if (condition)
            {
                x = a;
            }
            else
            {
                x = b;
            }
            return x;
        }

        public static Double IIF(bool condition, double a, double b)
        {
            double x = 0;
            if (condition)
            {
                x = a;
            }
            else
            {
                x = b;
            }
            return x;
        }

        public static decimal IIF(bool condition, decimal a, decimal b)
        {
            decimal x = 0;
            if (condition)
            {
                x = a;
            }
            else
            {
                x = b;
            }
            return x;
        }

        public static string IIF(bool condition, string a, string b)
        {
            string x = string.Empty;
            if (condition)
            {
                x = a;
            }
            else
            {
                x = b;
            }
            return x;
        }

        public static T IIF<T>(bool condition, T a, T b)
        {
            T x;
            if (condition)
            {
                x = a;
            }
            else
            {
                x = b;
            }
            return x;
        }

        public static int Min(int a, int b)
        {
            if (a < b)
            {
                return a;
            }
            return b;
        }

        public static int Max(int a, int b)
        {
            if (a > b)
            {
                return a;
            }
            return b;
        }

        public static decimal Min(decimal a, decimal b)
        {
            if (a < b)
            {
                return a;
            }
            return b;
        }

        public static decimal Max(decimal a, decimal b)
        {
            if (a > b)
            {
                return a;
            }
            return b;
        }

        public static Single Min(Single a, Single b)
        {
            if (a < b)
            {
                return a;
            }
            return b;
        }

        public static Single Max(Single a, Single b)
        {
            if (a > b)
            {
                return a;
            }
            return b;
        }

        public static DateTime Min(DateTime a, DateTime b)
        {
            if (a < b)
            {
                return a;
            }
            return b;
        }

        public static DateTime Max(DateTime a, DateTime b)
        {
            if (a > b)
            {
                return a;
            }
            return b;
        }

        public static string PageInvocation()
        {
            return HttpContext.Current.Request.RawUrl;
        }

        public static string PageReferrer()
        {
            try
            {
                if (HttpContext.Current.Request.UrlReferrer == null)
                {
                    return string.Empty;
                }
                else
                {
                    return HttpContext.Current.Request.UrlReferrer.ToString();
                }
            }
            catch
            { }
            return string.Empty;
        }

        public static string GetThisPageName(bool includePath)
        {
            string s = CommonLogic.ServerVariables("SCRIPT_NAME");
            if (!includePath)
            {
                int ix = s.LastIndexOf("/");
                if (ix != -1)
                {
                    s = s.Substring(ix + 1);
                }
            }
            return s;
        }

        //Thread safe current page name
        public static string GetCurrentPageName(HttpContext context)
        {
            string sPath = context.Request.PhysicalPath;
            System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
            string sRet = oInfo.Name;
            return sRet;
        }

        private const string STORE_VERSION_CACHE_KEY = "StoreVersionCacheKey";

        public static string GetVersion()
        {
            object cachedValue = HttpRuntime.Cache.Get(STORE_VERSION_CACHE_KEY);

            string version = string.Empty;

            if (cachedValue != null && cachedValue is string)
            {
                version = (string)cachedValue;
            }
            else
            {
                version = GetVersionCore();

                // Cache this indefinitely since the version wouldn't change for the lifetime of the WebSite
                HttpRuntime.Cache.Insert(STORE_VERSION_CACHE_KEY, version,
                    null,
                    Cache.NoAbsoluteExpiration,
                    Cache.NoSlidingExpiration);
            }

            if (IsStringNullOrEmpty(version))
            {
                version = GetVersionCore();
            }

            return version;
        }

        public static string GetVersionNumber()
        {
            return GetVersionCore(true);
        }

        private static string GetVersionCore(bool versionNumberOnly = false)
        {
            Assembly assem = Assembly.GetExecutingAssembly();
            AssemblyName assemName = assem.GetName();

            if (versionNumberOnly == true) { return assemName.Version.ToString(); }

            var productAttribute = assem
                .GetCustomAttributes(typeof(AssemblyProductAttribute), false)
                .OfType<AssemblyProductAttribute>()
                .FirstOrDefault();
            return "{0} {1}/{2}".FormatWith(productAttribute.Product, AppLogic.GetStoreVersion().Trim(), assemName.Version.ToString());
        }

        public static string GetPhoneDisplayFormat(string PhoneNumber)
        {
            if (PhoneNumber.Length == 0)
            {
                return string.Empty;
            }
            if (PhoneNumber.Length != 11)
            {
                return PhoneNumber;
            }
            return "(" + PhoneNumber.Substring(1, 3) + ") " + PhoneNumber.Substring(4, 3) + "-" + PhoneNumber.Substring(7, 4);
        }

        public static bool IsNumber(string expression)
        {
            if (expression.Trim().Length == 0)
            {
                return false;
            }
            expression = expression.Trim();
            bool hasDecimal = false;
            int startIdx = 0;
            if (expression.StartsWith("-"))
            {
                startIdx = 1;
            }
            for (int i = startIdx; i < expression.Length; i++)
            {
                // Check for decimal
                if (expression[i] == '.')
                {
                    if (hasDecimal) // 2nd decimal
                    {
                        return false;
                    }
                    else // 1st decimal
                    {
                        // inform loop decimal found and continue 
                        hasDecimal = true;
                        continue;
                    }
                }
                // check if number
                if (!char.IsNumber(expression[i]))
                {
                    return false;
                }
            }
            return true;
        }

        public static bool IsInteger(string expression)
        {
            if (expression.Trim().Length == 0)
            {
                return false;
            }
            // leading - is ok
            expression = expression.Trim();
            int startIdx = 0;
            if (expression.StartsWith("-"))
            {
                startIdx = 1;
            }
            for (int i = startIdx; i < expression.Length; i++)
            {
                if (!char.IsNumber(expression[i]))
                {
                    return false;
                }
            }
            return true;
        }

        public static bool IsDate(string expression)
        {
            if (expression.Trim().Length == 0)
            {
                return false;
            }
            try
            {
                DateTime.Parse(expression);
                return true;
            }
            catch
            {
                return false;
            }
        }
        public static int GetRandomNumber(int lowerBound, int upperBound)
        {
            return new System.Random().Next(lowerBound, upperBound + 1);
        }

        public static string GetExceptionDetail(Exception ex, string LineSeparator)
        {
            string ExDetail = "Exception=" + ex.Message + LineSeparator;
            while (ex.InnerException != null)
            {
                ExDetail += ex.InnerException.Message + LineSeparator;
                ex = ex.InnerException;
            }
            return ExDetail;
        }

        public static string HighlightTerm(string InString, string Term)
        {
            int i = InString.IndexOf(Term.ToUpperInvariant(), StringComparison.InvariantCultureIgnoreCase);
            if (i != -1)
            {
                InString = InString.Substring(0, i) + "<b>" + InString.Substring(i, Term.Length) + "</b>" + InString.Substring(i + Term.Length, InString.Length - Term.Length - i);
            }
            return InString;
        }

        public static string BuildStarsImage(Decimal d, int SkinID)
        {
            string s = string.Empty;
            if (d < 0.25M)
            {
                s = "<img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_" + SkinID.ToString() + "/images/stare.gif") + "\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\" />";
            }
            else if (d >= 0.25M && d < 0.75M)
            {
                s = "<img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_" + SkinID.ToString() + "/images/starh.gif") + "\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\" />";
            }
            else if (d >= 0.75M && d < 1.25M)
            {
                s = "<img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_" + SkinID.ToString() + "/images/starf.gif") + "\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\" />";
            }
            else if (d >= 1.25M && d < 1.75M)
            {
                s = "<img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_" + SkinID.ToString() + "/images/starf.gif") + "\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starh.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\" />";
            }
            else if (d >= 1.75M && d < 2.25M)
            {
                s = "<img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_" + SkinID.ToString() + "/images/starf.gif") + "\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starf.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\" />";
            }
            else if (d >= 2.25M && d < 2.75M)
            {
                s = "<img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_" + SkinID.ToString() + "/images/starf.gif") + "\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starf.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starh.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\" />";
            }
            else if (d >= 2.75M && d < 3.25M)
            {
                s = "<img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_" + SkinID.ToString() + "/images/starf.gif") + "\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starf.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starf.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\" />";
            }
            else if (d >= 3.25M && d < 3.75M)
            {
                s = "<img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_" + SkinID.ToString() + "/images/starf.gif") + "\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starf.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starf.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starh.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\" />";
            }
            else if (d >= 3.75M && d < 4.25M)
            {
                s = "<img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_" + SkinID.ToString() + "/images/starf.gif") + "\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starf.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starf.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starf.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/stare.gif\" />";
            }
            else if (d >= 4.25M && d < 4.75M)
            {
                s = "<img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_" + SkinID.ToString() + "/images/starf.gif") + "\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starf.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starf.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starf.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starh.gif\" />";
            }
            else if (d >= 4.75M)
            {
                s = "<img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_" + SkinID.ToString() + "/images/starf.gif") + "\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starf.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starf.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starf.gif\"><img align=\"absmiddle\" src=\"skins/skin_" + SkinID.ToString() + "/images/starf.gif\" />";
            }
            return s;
        }

        public static string Left(string s, int l)
        {
            if (s.Length <= l)
            {
                return s;
            }
            return s.Substring(0, l - 1);
        }

        public static string Ellipses(string s, int l, bool BreakBetweenWords)
        {
            if (l < 1)
            {
                return string.Empty;
            }
            if (l >= s.Length)
            {
                return s;
            }
            string tmpS = Left(s, l - 2);
            if (BreakBetweenWords)
            {
                try
                {
                    tmpS = tmpS.Substring(0, tmpS.LastIndexOf(" "));
                }
                catch { }
            }
            tmpS += "...";
            return tmpS;
        }

        public static string AspHTTP(string url, int TimeoutSecs)
        {
            string result;
            try
            {
                WebResponse objResponse;
                WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
                if (TimeoutSecs > 0)
                {
                    objRequest.Timeout = TimeoutSecs * 1000; // ms
                }
                else
                {
                    objRequest.Timeout = System.Threading.Timeout.Infinite;
                }
                objResponse = objRequest.GetResponse();
                using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                    // Close and clean up the StreamReader
                    sr.Close();
                }
                objResponse.Close();
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }

        public static string AspHTTP(string url, int TimeoutSecs, string postData)
        {
            string result;
            try
            {
                WebResponse objResponse;
                WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
                objRequest.ContentType = "application/x-www-form-urlencoded";
                objRequest.Method = "POST";
                UTF8Encoding encoder = new UTF8Encoding();
                byte[] bytearray = encoder.GetBytes(postData);
                objRequest.ContentLength = bytearray.Length;
                Stream reqStream = objRequest.GetRequestStream();
                reqStream.Write(bytearray, 0, bytearray.Length);
                reqStream.Close();

                if (TimeoutSecs > 0)
                {
                    objRequest.Timeout = TimeoutSecs * 1000;
                }
                else
                {
                    objRequest.Timeout = System.Threading.Timeout.Infinite;
                }
                objResponse = objRequest.GetResponse();
                using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                    // Close and clean up the StreamReader
                    sr.Close();
                }
                objResponse.Close();
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }

        public static string SelectOption(string activeValue, string oname, string fieldname)
        {
            if (activeValue == oname)
            {
                return " selected";
            }
            else
            {
                return string.Empty;
            }
        }

        public static string SelectOption(IDataReader rs, string oname, string fieldname)
        {
            return SelectOption(DB.RSField(rs, fieldname), oname, fieldname);
        }

        public static string MakeFullName(string fn, string ln)
        {
            string tmp = fn + " " + ln;
            return tmp.Trim();
        }

        public static string ExtractBody(string ss, bool plainTextOk)
        {
            try
            {
                int startAt;
                int stopAt;
                startAt = ss.IndexOf("<body");
                if (startAt == -1)
                {
                    startAt = ss.IndexOf("<BODY");
                }
                if (startAt == -1)
                {
                    startAt = ss.IndexOf("<Body");
                }

                if (startAt >= 0)
                {
                    //Do not run this code if value is -1 or it will create an error.
                    startAt = ss.IndexOf(">", startAt);
                }
                else
                {
                    return ss;
                }

                stopAt = ss.IndexOf("</body>");
                if (stopAt == -1)
                {
                    stopAt = ss.IndexOf("</BODY>");
                }
                if (stopAt == -1)
                {
                    stopAt = ss.IndexOf("</Body>");
                }
                if (startAt == -1)
                {
                    startAt = 1;
                }
                else
                {
                    startAt = startAt + 1;
                }
                if (stopAt == -1)
                {
                    stopAt = ss.Length;
                }
                //body
                string body = ss.Substring(startAt, stopAt - startAt);


                int stylestart;
                int stylestop;

                stylestart = ss.IndexOf("<style");
                if (stylestart == -1)
                {
                    stylestart = ss.IndexOf("<STYLE");
                }

                if (stylestart == -1)
                {
                    stylestop = ss.IndexOf("<Style>");
                }

                if (stylestart == -1)
                {
                    //stylestart = 1;
                    return body;
                }

                //end of Style tag

                stylestop = ss.IndexOf("</style");
                if (stylestop == -1)
                {
                    stylestop = ss.IndexOf("</STYLE");
                }
                if (stylestop == -1)
                {
                    stylestop = ss.IndexOf("</Style");
                }

                if (stylestop == -1)
                {
                    stylestop = ss.Length;
                }

                stylestop = ss.IndexOf(">", stylestop);
                stylestop = stylestop + 1;

                string style;
                style = ss.Substring(stylestart, stylestop - stylestart);

                // body and span
                return string.Concat(style, Environment.NewLine, body);
            }
            catch
            {
                if (plainTextOk)
                {
                    return ss;
                }
                return string.Empty;
            }
        }

        public static void WriteFile(string fname, string contents, bool WriteFileInUTF8)
        {
            fname = SafeMapPath(fname);
            StreamWriter wr;
            if (WriteFileInUTF8)
            {
                wr = new StreamWriter(fname, false, System.Text.Encoding.UTF8, 4096);
            }
            else
            {
                wr = new StreamWriter(fname, false, System.Text.Encoding.ASCII, 4096);
            }
            wr.Write(contents);
            wr.Flush();
            wr.Close();
        }

        public static string ReadFile(string fname, bool ignoreErrors)
        {
            string contents;
            try
            {
                fname = SafeMapPath(fname);
                StreamReader rd = new StreamReader(fname);
                contents = rd.ReadToEnd();
                rd.Close();
                return contents;
            }
            catch (Exception e)
            {
                if (ignoreErrors)
                    return string.Empty;
                else
                    throw e;
            }
        }

        public static string Capitalize(string s)
        {
            if (s.Length == 0)
            {
                return string.Empty;
            }
            else if (s.Length == 1)
            {
                return s.ToUpper(CultureInfo.InvariantCulture);
            }
            else
            {
                return s.Substring(0, 1).ToUpper(CultureInfo.InvariantCulture) + s.Substring(1, s.Length - 1).ToLower();
            }
        }

        public static string ServerVariables(string paramName)
        {
            string tmpS = string.Empty;
            if (HttpContext.Current.Request.ServerVariables[paramName] != null)
            {
                try
                {
                    tmpS = HttpContext.Current.Request.ServerVariables[paramName].ToString();
                }
                catch
                {
                    tmpS = string.Empty;
                }
            }
            return tmpS;
        }

        //Threading purpose
        public static string ServerVariables(HttpContext context, string paramName)
        {
            string tmpS = string.Empty;
            if (context.Request.ServerVariables[paramName] != null)
            {
                try
                {
                    tmpS = context.Request.ServerVariables[paramName].ToString();
                }
                catch
                {
                    tmpS = string.Empty;
                }
            }
            return tmpS;
        }

        // can take virtual fname, or fully qualified path fname
        public static bool FileExists(string fname)
        {
            return File.Exists(SafeMapPath(fname));
        }

        // this is probably the implementation that Microsoft SHOULD have done!
        // use this helper function for ALL MapPath calls in the entire site for safety!
        public static string SafeMapPath(string fname)
        {
            if (fname.StartsWith("\\\\"))
            {
                return fname;
            }

            string result = fname;

            //Try it as a virtual path. Try to map it based on the Request.MapPath to handle Medium trust level and "~/" paths automatically 
            try
            {
                result = HttpContext.Current.Server.MapPath(fname);
            }
            catch
            {
                //Didn't like something about the virtual path.
                //May be a drive path. See if it will expand to a valid path
                try
                {
                    //Try a GetFullPath. If the path is not virtual or has other malformed problems
                    //Return it as is
                    result = Path.GetFullPath(fname);
                }
                catch (NotSupportedException) // Contains a colon, probably already a full path.
                {
                    return fname;
                }
                catch (SecurityException exc)//Path is somewhere you're not allowed to access or is otherwise damaged
                {
                    throw new SecurityException("If you are running in Medium Trust you may have virtual directories defined that are not accessible at this trust level,\n " + exc.Message);
                }
            }
            return result;
        }


        public static string ExtractToken(string ss, string t1, string t2)
        {
            if (ss.Length == 0)
            {
                return string.Empty;
            }
            int i1 = ss.IndexOf(t1);
            int i2 = ss.IndexOf(t2, CommonLogic.IIF(i1 == -1, 0, i1));
            if (i1 == -1 || i2 == -1 || i1 >= i2 || (i2 - i1) <= 0)
            {
                return string.Empty;
            }
            return ss.Substring(i1, i2 - i1).Replace(t1, "");
        }

        public static void SetField(DataSet ds, string fieldname)
        {
            ds.Tables["Customers"].Rows[0][fieldname] = CommonLogic.FormCanBeDangerousContent(fieldname);
        }

        public static string MakeSafeJavascriptName(string s)
        {
            string OKChars = "abcdefghijklmnopqrstuvwxyz1234567890_";
            s = s.ToLowerInvariant();
            StringBuilder tmpS = new StringBuilder(s.Length);
            for (int i = 0; i < s.Length; i++)
            {
                string tok = s.Substring(i, 1);
                if (OKChars.IndexOf(tok) != -1)
                {
                    tmpS.Append(tok);
                }
            }
            return tmpS.ToString();
        }

        public static string MakeSafeFilesystemName(string s)
        {
            string OKChars = "abcdefghijklmnopqrstuvwxyz1234567890_";
            s = s.ToLowerInvariant();
            StringBuilder tmpS = new StringBuilder(s.Length);
            for (int i = 0; i < s.Length; i++)
            {
                string tok = s.Substring(i, 1);
                if (OKChars.IndexOf(tok) != -1)
                {
                    tmpS.Append(tok);
                }
            }
            return tmpS.ToString();
        }

        public static string MakeSafeJavascriptString(string s)
        {
            return s.Replace("'", "\\'").Replace("\"", "\\\"");
        }

        /// <summary>
        /// Encodes a string to be represented as a string literal. The format
        /// is essentially a JSON string.
        /// 
        /// The string returned includes outer quotes 
        /// Example Output: "Hello \"Rick\"!\r\nRock on"
        /// </summary>
        /// <param name="s">The string to encode</param>
        /// <returns>The encoded string.</returns>
        //This code came from http://www.west-wind.com/weblog/posts/114530.aspx
        public static string JSStringEncode(string stringToEncode)
        {
            StringBuilder returnValue = new StringBuilder();
            returnValue.Append("\"");
            foreach (char currentChar in stringToEncode)
            {
                switch (currentChar)
                {
                    case '\"':
                        returnValue.Append("\\\"");
                        break;
                    case '\\':
                        returnValue.Append("\\\\");
                        break;
                    case '\b':
                        returnValue.Append("\\b");
                        break;
                    case '\f':
                        returnValue.Append("\\f");
                        break;
                    case '\n':
                        returnValue.Append("\\n");
                        break;
                    case '\r':
                        returnValue.Append("\\r");
                        break;
                    case '\t':
                        returnValue.Append("\\t");
                        break;
                    default:
                        int i = (int)currentChar;
                        if (i < 32 || i > 127)
                        {
                            returnValue.AppendFormat("\\u{0:X04}", i);
                        }
                        else
                        {
                            returnValue.Append(currentChar);
                        }
                        break;
                }
            }
            returnValue.Append("\"");

            return returnValue.ToString();
        }

        /// <summary>
        /// Reads data into a complete array, throwing an EndOfStreamException
        /// if the stream runs out of data first, or if an IOException
        /// naturally occurs.
        /// </summary>
        /// <param name="stream">The stream to read data from</param>
        /// <param name="data">The array to read bytes into. The array
        /// will be completely filled from the stream, so an appropriate
        /// size must be given.</param>
        public static void ReadWholeArray(Stream stream, byte[] data)
        {
            int offset = 0;
            int remaining = data.Length;
            while (remaining > 0)
            {
                int read = stream.Read(data, offset, remaining);
                if (read <= 0)
                {
                    return;
                }
                remaining -= read;
            }
        }

        /// <summary>
        /// Reads data from a stream until the end is reached. The
        /// data is returned as a byte array. An IOException is
        /// thrown if any of the underlying IO calls fail.
        /// </summary>
        public static byte[] ReadFully(Stream stream)
        {
            byte[] buffer = new byte[32768];
            using (MemoryStream ms = new MemoryStream())
            {
                while (true)
                {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                    {
                        return ms.ToArray();
                    }
                    ms.Write(buffer, 0, read);
                }
            }
        }

        public static Size GetImagePixelSize(string imgname)
        {
            try
            {
                //create instance of Bitmap class around specified image file
                // must use try/catch in case the image file is bogus
                using (Bitmap img = new Bitmap(SafeMapPath(imgname), false))
                {
                    return new Size(img.Width, img.Height);
                }
            }
            catch
            {
                return new Size(0, 0);
            }
        }

        public static string WrapString(string s, int ColWidth, string Separator)
        {
            StringBuilder tmpS = new StringBuilder(s.Length + 100);
            if (s.Length <= ColWidth || ColWidth == 0)
            {
                return s;
            }
            int start = 0;
            int length = Min(ColWidth, s.Length);
            while (start < s.Length)
            {
                if (tmpS.Length != 0)
                {
                    tmpS.Append(Separator);
                }
                tmpS.Append(s.Substring(start, length));
                start += ColWidth;
                length = Min(ColWidth, s.Length - start);
            }
            return tmpS.ToString();
        }

        public static string GetNewGUID()
        {
            return System.Guid.NewGuid().ToString().ToUpperInvariant();
        }

        public static string HtmlEncode(string S)
        {
            string result = string.Empty;
            for (int i = 0; i < S.Length; i++)
            {
                string c = S.Substring(i, 1);
                int acode = (int)c[0];
                if (acode < 32 || acode > 127)
                {
                    result += "&#" + acode.ToString() + ";";
                }
                else
                {
                    switch (acode)
                    {
                        case 32:
                            result += "&nbsp;";
                            break;
                        case 34:
                            result += "&quot;";
                            break;
                        case 38:
                            result += "&amp;";
                            break;
                        case 60:
                            result += "&lt;";
                            break;
                        case 62:
                            result += "&gt;";
                            break;
                        default:
                            result += c;
                            break;
                    }
                }
            }
            return result;
        }

        // this version is NOT to be used to squote db sql stuff!
        public static string SQuote(string s)
        {
            return "'" + s.Replace("'", "''") + "'";
        }


        // this version is NOT to be used to squote db sql stuff!
        public static string DQuote(string s)
        {
            return "\"" + s.Replace("\"", "\"\"") + "\"";
        }

        // ----------------------------------------------------------------
        //
        // PARAMS SUPPORT ROUTINES Uses Request.Params[]
        //
        // ----------------------------------------------------------------

        public static string ParamsCanBeDangerousContent(string paramName)
        {
            string tmpS = string.Empty;
            if (HttpContext.Current.Request.Params[paramName] != null)
            {
                try
                {
                    tmpS = HttpContext.Current.Request.Params[paramName];
                }
                catch
                {
                    tmpS = string.Empty;
                }
            }
            tmpS = Security.UrlEncode(tmpS);
            return tmpS;
        }

        public static bool ParamsBool(string paramName)
        {
            string tmpS = ParamsCanBeDangerousContent(paramName);

            return "TRUE".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase) ||
                    "YES".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase) ||
                    "1".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase);
        }

        public static int ParamsUSInt(string paramName)
        {
            string tmpS = ParamsCanBeDangerousContent(paramName);
            return Localization.ParseUSInt(tmpS);
        }

        public static long ParamsUSLong(string paramName)
        {
            string tmpS = ParamsCanBeDangerousContent(paramName);
            return Localization.ParseUSLong(tmpS);
        }

        public static Single ParamsUSSingle(string paramName)
        {
            string tmpS = ParamsCanBeDangerousContent(paramName);
            return Localization.ParseUSSingle(tmpS);
        }

        public static Double ParamsUSDouble(string paramName)
        {
            string tmpS = ParamsCanBeDangerousContent(paramName);
            return Localization.ParseUSDouble(tmpS);
        }

        public static decimal ParamsUSDecimal(string paramName)
        {
            string tmpS = ParamsCanBeDangerousContent(paramName);
            return Localization.ParseUSDecimal(tmpS);
        }

        public static DateTime ParamsUSDateTime(string paramName)
        {
            string tmpS = ParamsCanBeDangerousContent(paramName);
            return Localization.ParseUSDateTime(tmpS);
        }

        public static int ParamsNativeInt(string paramName)
        {
            string tmpS = ParamsCanBeDangerousContent(paramName);
            return Localization.ParseNativeInt(tmpS);
        }

        public static long ParamsNativeLong(string paramName)
        {
            string tmpS = ParamsCanBeDangerousContent(paramName);
            return Localization.ParseNativeLong(tmpS);
        }

        public static Single ParamsNativeSingle(string paramName)
        {
            string tmpS = ParamsCanBeDangerousContent(paramName);
            return Localization.ParseNativeSingle(tmpS);
        }

        public static Double ParamsNativeDouble(string paramName)
        {
            string tmpS = ParamsCanBeDangerousContent(paramName);
            return Localization.ParseNativeDouble(tmpS);
        }

        public static decimal ParamsNativeDecimal(string paramName)
        {
            string tmpS = ParamsCanBeDangerousContent(paramName);
            return Localization.ParseNativeDecimal(tmpS);
        }

        public static DateTime ParamsNativeDateTime(string paramName)
        {
            string tmpS = ParamsCanBeDangerousContent(paramName);
            return Localization.ParseNativeDateTime(tmpS);
        }

        // ----------------------------------------------------------------
        //
        // FORM SUPPORT ROUTINES
        //
        // ----------------------------------------------------------------
        public static string FormCanBeDangerousContent(string paramName)
        {
            return FormCanBeDangerousContent(paramName, false);
        }

        public static string FormCanBeDangerousContent(string paramName, bool decode)
        {
            string tmpS = string.Empty;
            if (HttpContext.Current.Request.Form[paramName] != null)
            {
                try
                {
                    tmpS = HttpContext.Current.Request.Form[paramName].ToString();
                }
                catch
                {
                    tmpS = string.Empty;
                }
            }

            tmpS = CommonLogic.IIF(decode, Security.HtmlDecode(tmpS), tmpS);
            return tmpS;
        }

        public static bool FormBool(string paramName)
        {
            string tmpS = FormCanBeDangerousContent(paramName);

            return "TRUE".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase) ||
                    "YES".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase) ||
                    "1".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase);
        }

        public static Guid? FormGuid(string paramName)
        {
            string tmpS = FormCanBeDangerousContent(paramName);
            return tmpS.TryParseGuid();
        }

        public static int FormUSInt(string paramName)
        {
            string tmpS = FormCanBeDangerousContent(paramName);
            return Localization.ParseUSInt(tmpS);
        }

        public static long FormUSLong(string paramName)
        {
            string tmpS = FormCanBeDangerousContent(paramName);
            return Localization.ParseUSLong(tmpS);
        }

        public static Single FormUSSingle(string paramName)
        {
            string tmpS = FormCanBeDangerousContent(paramName);
            return Localization.ParseUSSingle(tmpS);
        }

        public static Double FormUSDouble(string paramName)
        {
            string tmpS = FormCanBeDangerousContent(paramName);
            return Localization.ParseUSDouble(tmpS);
        }

        public static decimal FormUSDecimal(string paramName)
        {
            string tmpS = FormCanBeDangerousContent(paramName);
            return Localization.ParseUSDecimal(tmpS);
        }

        public static DateTime FormUSDateTime(string paramName)
        {
            string tmpS = FormCanBeDangerousContent(paramName);
            return Localization.ParseUSDateTime(tmpS);
        }

        public static int FormNativeInt(string paramName)
        {
            string tmpS = FormCanBeDangerousContent(paramName);
            return Localization.ParseNativeInt(tmpS);
        }

        public static long FormNativeLong(string paramName)
        {
            string tmpS = FormCanBeDangerousContent(paramName);
            return Localization.ParseNativeLong(tmpS);
        }

        public static Single FormNativeSingle(string paramName)
        {
            string tmpS = FormCanBeDangerousContent(paramName);
            return Localization.ParseNativeSingle(tmpS);
        }

        public static Double FormNativeDouble(string paramName)
        {
            string tmpS = FormCanBeDangerousContent(paramName);
            return Localization.ParseNativeDouble(tmpS);
        }

        public static decimal FormNativeDecimal(string paramName)
        {
            string tmpS = FormCanBeDangerousContent(paramName);
            return Localization.ParseNativeDecimal(tmpS);
        }

        public static DateTime FormNativeDateTime(string paramName)
        {
            string tmpS = FormCanBeDangerousContent(paramName);
            return Localization.ParseNativeDateTime(tmpS);
        }

        public static Decimal FormLocaleDecimal(string paramName, string LocaleSetting)
        {
            string tmpS = FormCanBeDangerousContent(paramName);
            return Localization.ParseLocaleDecimal(tmpS,LocaleSetting);
        }

        // ----------------------------------------------------------------
        //
        // QUERYSTRING SUPPORT ROUTINES
        //
        // ----------------------------------------------------------------
        public static string QueryStringCanBeDangerousContent(string paramName)
        {
            return QueryStringCanBeDangerousContent(paramName, false);
        }

        public static string QueryStringCanBeDangerousContent(string paramName, bool decode)
        {
            string tmpS = string.Empty;
            if (HttpContext.Current.Request.QueryString[paramName] != null)
            {
                try
                {
                    tmpS = HttpContext.Current.Request.QueryString[paramName].ToString();
                }
                catch
                {
                    tmpS = string.Empty;
                }
            }

            if (decode)
            {
                tmpS = Security.UrlDecode(tmpS);
            }

            return tmpS;
        }

        public static bool QueryStringBool(string paramName)
        {
            string tmpS = QueryStringCanBeDangerousContent(paramName);

            return "TRUE".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase) ||
                    "YES".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase) ||
                    "1".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase);
        }

        public static int QueryStringUSInt(string paramName)
        {
            string tmpS = QueryStringCanBeDangerousContent(paramName);
            return Localization.ParseUSInt(tmpS);
        }

        public static long QueryStringUSLong(string paramName)
        {
            string tmpS = QueryStringCanBeDangerousContent(paramName);
            return Localization.ParseUSLong(tmpS);
        }

        public static Single QueryStringUSSingle(string paramName)
        {
            string tmpS = QueryStringCanBeDangerousContent(paramName);
            return Localization.ParseUSSingle(tmpS);
        }

        public static Double QueryStringUSDouble(string paramName)
        {
            string tmpS = QueryStringCanBeDangerousContent(paramName);
            return Localization.ParseUSDouble(tmpS);
        }

        public static decimal QueryStringUSDecimal(string paramName)
        {
            string tmpS = QueryStringCanBeDangerousContent(paramName);
            return Localization.ParseUSDecimal(tmpS);
        }

        public static DateTime QueryStringUSDateTime(string paramName)
        {
            string tmpS = QueryStringCanBeDangerousContent(paramName);
            return Localization.ParseUSDateTime(tmpS);
        }

        public static int QueryStringNativeInt(string paramName)
        {
            string tmpS = QueryStringCanBeDangerousContent(paramName);
            return Localization.ParseNativeInt(tmpS);
        }

        public static long QueryStringNativeLong(string paramName)
        {
            string tmpS = QueryStringCanBeDangerousContent(paramName);
            return Localization.ParseNativeLong(tmpS);
        }

        public static Single QueryStringNativeSingle(string paramName)
        {
            string tmpS = QueryStringCanBeDangerousContent(paramName);
            return Localization.ParseNativeSingle(tmpS);
        }

        public static Double QueryStringNativeDouble(string paramName)
        {
            string tmpS = QueryStringCanBeDangerousContent(paramName);
            return Localization.ParseNativeDouble(tmpS);
        }

        public static decimal QueryStringNativeDecimal(string paramName)
        {
            string tmpS = QueryStringCanBeDangerousContent(paramName);
            return Localization.ParseNativeDecimal(tmpS);
        }

        public static DateTime QueryStringNativeDateTime(string paramName)
        {
            string tmpS = QueryStringCanBeDangerousContent(paramName);
            return Localization.ParseNativeDateTime(tmpS);
        }

        public static string ApplicationIS(string paramName)
        {
            string tmpS = string.Empty;
            try
            {
                tmpS = InterpriseHelper.ConfigInstance.OnlineCompanyConnectionString;
                if (tmpS == null)
                {
                    tmpS = string.Empty;
                }
            }
            catch
            {
                tmpS = string.Empty;
            }
            return tmpS;
        }

        public static string Application(string paramName)
        {
            string tmpS = string.Empty;
            if (System.Web.Configuration.WebConfigurationManager.AppSettings[paramName] != null)
            {
                try
                {
                    tmpS = System.Web.Configuration.WebConfigurationManager.AppSettings[paramName];
                }
                catch
                {
                    tmpS = string.Empty;
                }
            }
            return tmpS;
        }

        public static bool ApplicationBool(string paramName)
        {
            string tmpS = Application(paramName);

            return "TRUE".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase) ||
                    "YES".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase) ||
                    "1".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase);
        }

        public static int ApplicationUSInt(string paramName)
        {
            string tmpS = Application(paramName);
            return Localization.ParseUSInt(tmpS);
        }

        public static long ApplicationUSLong(string paramName)
        {
            string tmpS = Application(paramName);
            return Localization.ParseUSLong(tmpS);
        }

        public static Single ApplicationUSSingle(string paramName)
        {
            string tmpS = Application(paramName);
            return Localization.ParseUSSingle(tmpS);
        }

        public static Double ApplicationUSDouble(string paramName)
        {
            string tmpS = Application(paramName);
            return Localization.ParseUSDouble(tmpS);
        }

        public static Decimal ApplicationUSDecimal(string paramName)
        {
            string tmpS = Application(paramName);
            return Localization.ParseUSDecimal(tmpS);
        }

        public static DateTime ApplicationUSDateTime(string paramName)
        {
            string tmpS = Application(paramName);
            return Localization.ParseUSDateTime(tmpS);
        }

        public static int ApplicationNativeInt(string paramName)
        {
            string tmpS = Application(paramName);
            return Localization.ParseNativeInt(tmpS);
        }

        public static long ApplicationNativeLong(string paramName)
        {
            string tmpS = Application(paramName);
            return Localization.ParseNativeLong(tmpS);
        }

        public static Single ApplicationNativeSingle(string paramName)
        {
            string tmpS = Application(paramName);
            return Localization.ParseNativeSingle(tmpS);
        }

        public static Double ApplicationNativeDouble(string paramName)
        {
            string tmpS = Application(paramName);
            return Localization.ParseNativeDouble(tmpS);
        }

        public static Decimal ApplicationNativeDecimal(string paramName)
        {
            string tmpS = Application(paramName);
            return Localization.ParseNativeDecimal(tmpS);
        }

        public static DateTime ApplicationNativeDateTime(string paramName)
        {
            string tmpS = Application(paramName);
            return Localization.ParseNativeDateTime(tmpS);
        }

        // ----------------------------------------------------------------
        //
        // COOKIE SUPPORT ROUTINES
        //
        // ----------------------------------------------------------------
        public static string CookieCanBeDangerousContent(string paramName, bool decode)
        {
            if (HttpContext.Current.Request.Cookies[paramName] == null)
            {
                return string.Empty;
            }
            try
            {
                string tmp = HttpContext.Current.Request.Cookies[paramName].Value.ToString();
                if (decode)
                {
                    tmp = HttpContext.Current.Server.UrlDecode(tmp);
                }
                return tmp;
            }
            catch
            {
                return string.Empty;
            }
        }

        public static bool CookieBool(string paramName)
        {
            string tmpS = CookieCanBeDangerousContent(paramName, true);

            return "TRUE".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase) ||
                    "YES".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase) ||
                    "1".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase);
        }

        public static int CookieUSInt(string paramName)
        {
            string tmpS = CookieCanBeDangerousContent(paramName, true);
            return Localization.ParseUSInt(tmpS);
        }

        public static long CookieUSLong(string paramName)
        {
            string tmpS = CookieCanBeDangerousContent(paramName, true);
            return Localization.ParseUSLong(tmpS);
        }

        public static Single CookieUSSingle(string paramName)
        {
            string tmpS = CookieCanBeDangerousContent(paramName, true);
            return Localization.ParseUSSingle(tmpS);
        }

        public static Double CookieUSDouble(string paramName)
        {
            string tmpS = CookieCanBeDangerousContent(paramName, true);
            return Localization.ParseUSDouble(tmpS);
        }

        public static Decimal CookieUSDecimal(string paramName)
        {
            string tmpS = CookieCanBeDangerousContent(paramName, true);
            return Localization.ParseUSDecimal(tmpS);
        }

        public static DateTime CookieUSDateTime(string paramName)
        {
            string tmpS = CookieCanBeDangerousContent(paramName, true);
            return Localization.ParseUSDateTime(tmpS);
        }

        public static int CookieNativeInt(string paramName)
        {
            string tmpS = CookieCanBeDangerousContent(paramName, true);
            return Localization.ParseNativeInt(tmpS);
        }

        public static long CookieNativeLong(string paramName)
        {
            string tmpS = CookieCanBeDangerousContent(paramName, true);
            return Localization.ParseNativeLong(tmpS);
        }

        public static Single CookieNativeSingle(string paramName)
        {
            string tmpS = CookieCanBeDangerousContent(paramName, true);
            return Localization.ParseNativeSingle(tmpS);
        }

        public static Double CookieNativeDouble(string paramName)
        {
            string tmpS = CookieCanBeDangerousContent(paramName, true);
            return Localization.ParseNativeDouble(tmpS);
        }

        public static Decimal CookieNativeDecimal(string paramName)
        {
            string tmpS = CookieCanBeDangerousContent(paramName, true);
            return Localization.ParseNativeDecimal(tmpS);
        }

        public static DateTime CookieNativeDateTime(string paramName)
        {
            string tmpS = CookieCanBeDangerousContent(paramName, true);
            return Localization.ParseNativeDateTime(tmpS);
        }


        // ----------------------------------------------------------------
        //
        // Hashtable PARAM SUPPORT ROUTINES
        // assumes has table has string keys, and string values.
        //
        // ----------------------------------------------------------------
        public static string HashtableParam(Hashtable t, string paramName)
        {
            string tmpS = string.Empty;
            if (t[paramName] != null)
            {
                try
                {
                    tmpS = t[paramName].ToString();
                }
                catch
                {
                    tmpS = string.Empty;
                }
            }
            return tmpS;
        }

        public static bool HashtableParamBool(Hashtable t, string paramName)
        {
            string tmpS = CommonLogic.HashtableParam(t, paramName);

            return "TRUE".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase) ||
                    "YES".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase) ||
                    "1".Equals(tmpS, StringComparison.InvariantCultureIgnoreCase);
        }

        public static int HashtableParamUSInt(Hashtable t, string paramName)
        {
            string tmpS = HashtableParam(t, paramName);
            return Localization.ParseUSInt(tmpS);
        }

        public static long HashtableParamUSLong(Hashtable t, string paramName)
        {
            string tmpS = HashtableParam(t, paramName);
            return Localization.ParseUSLong(tmpS);
        }

        public static Single HashtableParamUSSingle(Hashtable t, string paramName)
        {
            string tmpS = HashtableParam(t, paramName);
            return Localization.ParseUSSingle(tmpS);
        }

        public static Double HashtableParamUSDouble(Hashtable t, string paramName)
        {
            string tmpS = HashtableParam(t, paramName);
            return Localization.ParseUSDouble(tmpS);
        }

        public static decimal HashtableParamUSDecimal(Hashtable t, string paramName)
        {
            string tmpS = HashtableParam(t, paramName);
            return Localization.ParseUSDecimal(tmpS);
        }

        public static DateTime HashtableParamUSDateTime(Hashtable t, string paramName)
        {
            string tmpS = HashtableParam(t, paramName);
            return Localization.ParseUSDateTime(tmpS);
        }

        public static int HashtableParamNativeInt(Hashtable t, string paramName)
        {
            string tmpS = HashtableParam(t, paramName);
            return Localization.ParseNativeInt(tmpS);
        }

        public static long HashtableParamNativeLong(Hashtable t, string paramName)
        {
            string tmpS = HashtableParam(t, paramName);
            return Localization.ParseNativeLong(tmpS);
        }

        public static Single HashtableParamNativeSingle(Hashtable t, string paramName)
        {
            string tmpS = HashtableParam(t, paramName);
            return Localization.ParseNativeSingle(tmpS);
        }

        public static Double HashtableParamNativeDouble(Hashtable t, string paramName)
        {
            string tmpS = HashtableParam(t, paramName);
            return Localization.ParseNativeDouble(tmpS);
        }

        public static decimal HashtableParamNativeDecimal(Hashtable t, string paramName)
        {
            string tmpS = HashtableParam(t, paramName);
            return Localization.ParseNativeDecimal(tmpS);
        }

        public static DateTime HashtableParamNativeDateTime(Hashtable t, string paramName)
        {
            string tmpS = HashtableParam(t, paramName);
            return Localization.ParseNativeDateTime(tmpS);
        }

        #region Address Validation
        /// <summary>
        /// Check Address Information if all Values are valid,
        /// If Not return the necessary flag (in strings)
        /// </summary>
        /// <param name="addressInfo">Address Object</param>
        /// <param name="countryInfo">Country Object</param>
        /// <returns>
        /// flags[strings]:
        /// None(valid), 
        /// IsInvalidCityOnly,
        /// IsInvalidPostalOnly,
        /// IsInvalidPostalAndCity
        /// </returns>
        public static string CheckIfAddressIsCorrect(Address addressInfo, InterpriseSuiteEcommerceCommon.DTO.CountryAddressDTO countryInfo)
        {
            string resCheck = string.Empty;
            bool withState = countryInfo.withState;
            string sqlCheck = "exec eCommerceWebAddressChecker 0, {0}, {1}, {2}, {3}, '',0,'', {4}";

            if (countryInfo.searchablePostal)
            {
                using (System.Data.SqlClient.SqlConnection con = DB.NewSqlConnection())
                {
                    con.Open();
                    using (IDataReader rs = DB.GetRSFormat(con, sqlCheck, DB.SQuote(addressInfo.PostalCode), DB.SQuote(addressInfo.State), DB.SQuote(addressInfo.Country), DB.SQuote(addressInfo.City), withState))
                    {
                        if (rs.Read())
                        {
                            resCheck = DB.RSField(rs, "ReturnData").ToString();
                        }
                    }
                }
            }

            return resCheck;
        }
        #endregion Address Validation

        public static Decimal RoundQuantity(Decimal quantityValue)
        {
            return Math.Round(quantityValue, InterpriseHelper.GetInventoryDecimalPlacesPreference());
        }

        private static string[] GetAttributeGroupIDs()
        {
            string[] attGroupID = new string[] { };
            string param = CommonLogic.QueryStringCanBeDangerousContent("gid");

            if (param.Length > 0)
            {
                attGroupID = param.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
            }

            return attGroupID;
        }

        private static string[] GetAttributeIDs()
        {
            string[] attID = new string[] { };
            string param = CommonLogic.QueryStringCanBeDangerousContent("aid");

            if (param.Length > 0)
            {
                attID = param.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
            }

            return attID;
        }

        private static string[] GetAttributeGroupGUIDs()
        {
            string[] attguid = new string[] { };
            string param = CommonLogic.QueryStringCanBeDangerousContent("guid");

            if (param.Length > 0)
            {
                attguid = param.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
            }

            return attguid;
        }

        public static string GetAttributeFilter()
        {
            string filter = string.Empty;
            string[] attGroupID = GetAttributeGroupIDs();
            string[] attID = GetAttributeIDs();
            string[] guids = GetAttributeGroupGUIDs();

            if (attGroupID.Length > 0 && attID.Length > 0)
            {

                for (int i = 0; i <= attGroupID.Length; i++)
                {
                    if (attID.Length - 1 >= i && guids.Length - 1 >= i)
                    {
                        filter = string.Concat(filter, attGroupID[i], "-", attID[i], "-", guids[i], ",");
                    }
                }

            }

            if (filter.EndsWith(",")) { filter = filter.Remove(filter.Length - 1, 1); }

            return filter;
        }
    }

}






